package com.guet.controller;


import cn.hutool.core.bean.BeanUtil;
import com.guet.domain.User;
import com.guet.domain.UserInfo;
import com.guet.domain.dto.LoginFormDTO;
import com.guet.domain.dto.UserDTO;
import com.guet.service.UserInfoService;
import com.guet.service.UserService;
import com.guet.utils.Result;
import com.guet.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;


@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;
    @Resource
    private UserInfoService userInfoService;

    // 发送手机验证码
    @PostMapping("code")
    public Result sendCode(String phone) {
        return userService.sendCode(phone);
    }

    // 登录
    @PostMapping("/login")
    public Result login(@RequestBody LoginFormDTO loginForm){
        return userService.login(loginForm);
    }

    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result logout(){
        // TODO 实现登出功能
        return Result.fail("功能未完成");
    }

    /**
     * 当前用户(自己)的一些信息
     */
    @GetMapping("/me")
    public Result me(){
        UserDTO user = UserHolder.getUser();
        return Result.ok(user);
    }

    @GetMapping("/info/{id}")
    public Result info(@PathVariable("id") Long userId){
        // 查询详情
        UserInfo info = userInfoService.getById(userId);
        if (info == null) {
            // 没有详情，应该是第一次查看详情
            return Result.ok();
        }
        info.setCreateTime(null);
        info.setUpdateTime(null);
        // 返回
        return Result.ok(info);
    }

    /**
     * 指定用户的一些信息
     */
    @GetMapping("/{userId}")
    public Result queryUserById(@PathVariable Long userId){
        User user = userService.getById(userId);
        if (user == null) {
            return Result.ok();
        }
        UserDTO userDTO = BeanUtil.copyProperties(user, UserDTO.class);
        return Result.ok(userDTO);
    }

    /**
     * 用户签到
     */
    @PostMapping("/sign")
    public Result sign(){
        return userService.sign();
    }

    /**
     * 签到统计(截止今天向前的连续签到次数)
     */
    @GetMapping("/sign/count")
    public Result signCount(){
        return userService.signCount();
    }
}
